package com.logistics.dao;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import cn.easybuild.core.hibernate.StringPojoHibernateHandler;

import com.logistics.Orders;
import com.logistics.OrdersQueryParam;
import com.logistics.admin.DateUtils;

@Repository
public class OrdersDaoImpl extends StringPojoHibernateHandler<Orders> implements OrdersDao {

	@Override
	public List<Orders> query(final OrdersQueryParam param) {
		return queryWithParameter(param, "o", "o.createDate", new QueryCriteriaSetter() {

			@Override
			public void setCriteria(StringBuffer hql, Map<String, Object> value) {
				if (StringUtils.isNotBlank(param.getId())) {
					hql.append(" and id = :id");
					value.put("id", param.getId());
				}
				
				if (StringUtils.isNotBlank(param.getStartDate())) {
					hql.append(" and createDate >= :startDate");
					value.put("startDate",DateUtils.parseDateStratTime(param.getStartDate()));
				}
				
				if (StringUtils.isNotBlank(param.getEndDate())) {
					hql.append(" and createDate <= :endDate");
					value.put("endDate", DateUtils.parseDateEndTime(param.getEndDate()));
				}
			}
		});
	}

	@Override
	protected Class<Orders> getEntityClass() {
		return Orders.class;
	}

	@Override
	public Orders todayFinallyOrders() {
		StringBuffer hql = new StringBuffer("from ");
		hql.append(Orders.class.getName());
		hql.append(" where date(createDate) = date(?)");
		hql.append(" order by createDate desc");
		
		List<Orders> orders = query(hql.toString(), new Date());
		
		if (orders != null && orders.size() > 0) {
			return orders.get(0);
		}
		
		return null;
	}

}
